package cn.edu.gzhu.workOrderManagement.controller;

import cn.edu.gzhu.workOrderManagement.constants.MessageConstant;
import cn.edu.gzhu.workOrderManagement.enumeration.UserAuthorityEnum;
import cn.edu.gzhu.workOrderManagement.mapper.UserMapper;
import cn.edu.gzhu.workOrderManagement.pojo.dto.reminder.ReminderCreateDto;
import cn.edu.gzhu.workOrderManagement.pojo.dto.reminder.ReminderHistoryDto;
import cn.edu.gzhu.workOrderManagement.pojo.dto.reminder.ReminderReadDto;
import cn.edu.gzhu.workOrderManagement.pojo.entity.Reminder;
import cn.edu.gzhu.workOrderManagement.pojo.entity.User;
import cn.edu.gzhu.workOrderManagement.properties.JwtProperties;
import cn.edu.gzhu.workOrderManagement.result.Result;
import cn.edu.gzhu.workOrderManagement.service.ReminderService;
import cn.edu.gzhu.workOrderManagement.util.JwtUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.jsonwebtoken.Claims;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/reminder")
@Tag(name = "催单接口")
public class ReminderController {
    @Autowired
    JwtProperties jwtProperties;
    @Autowired
    ReminderService reminderService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RedisMessageListenerContainer redisMessageListenerContainer;
    @Autowired
    UserMapper userMapper;


    @PostMapping("/create")
    public Result postReminder(@RequestHeader String token,@Validated @RequestBody ReminderCreateDto reminderCreateDto){
        Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
        String username = claims.get("username").toString();
        Boolean res = reminderService.createReminder(username, reminderCreateDto);
        if(!res){
            return Result.error(MessageConstant.PARAMETER_ERROR);
        }

        return Result.success();
    }

    @GetMapping("/getNew")
    //分权限监听，总部监听自己权限的频道，分公司负责人等监听organization的频道，主管等监听teamId的通道
    public Result getNewReminder(@RequestHeader String token) {
        // 1️⃣ 解析 token 获取用户名
        Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
        String username = claims.get("username").toString();


        // 5️⃣ 获取用户信息
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));


        // 6️⃣ 构造监听频道名
        String channel;
        UserAuthorityEnum authority = user.getAuthority();
        int level = authority.getAuthority();

        if (level == 2) {
            channel = authority.name(); // HEAD_BUSINESS
        } else if (level == 3) {
            channel = user.getOrganization() + ":" + authority.name(); // Suzhou:BRANCH_BUSINESS
        } else if (level == 4) {
            channel = user.getOrganization() + ":" + user.getUsername(); // Suzhou:7
        } else {
            return Result.error(MessageConstant.PARAMETER_ERROR);
        }
        String pattern =  channel + ":*";
        // 7️⃣ 如果 Redis 中已有提醒，直接返回
        Set<String> keys = redisTemplate.keys(pattern);
        if (keys.isEmpty()) {
            return Result.success();
        }

        HashMap<String, Reminder> stringStringHashMap = new HashMap<>();
        for (String key : keys) {
            // 获取每个键对应的值
            Reminder value =  JSONUtil.toBean(redisTemplate.opsForValue().get(key).toString(),Reminder.class);  // 如果值是字符串类型
            if (value != null) {
                stringStringHashMap.put(key, value);
            }
        }
        return Result.success(stringStringHashMap);

    }


    @PostMapping("/read")
    public Result readReminder(@RequestHeader String token, @RequestBody ReminderReadDto reminderReadDto) {
        List<String> keys = reminderReadDto.getKeys();
        List<Reminder> reminders = reminderReadDto.getReminders();
        List<String> workOrderUuids = new ArrayList<>();
        List<LocalDateTime> times = new ArrayList<>();
        List<String> postUsernames = new ArrayList<>();
        for (Reminder reminder : reminders) {
            workOrderUuids.add(reminder.getWorkOrderUuid());
            times.add(reminder.getCreateTime());
            postUsernames.add(reminder.getPosterUsername());

        }
        redisTemplate.delete(keys);
        Boolean b = reminderService.readReminder(workOrderUuids, postUsernames, times);
        if(!b){
            return Result.error(MessageConstant.PARAMETER_ERROR);
        }
        return Result.success();

    }
    @GetMapping("getHistory")
    public Result getHistoryReminder(@RequestHeader String token, ReminderHistoryDto reminderHistoryDto ) {
        IPage historyReminder = reminderService.getHistoryReminder(reminderHistoryDto);
        return Result.success(historyReminder);
    }

    // 存储所有活跃的长轮询请求
    private static final ConcurrentHashMap<String, DeferredResult<Result>> reminderPollingMap = new ConcurrentHashMap<>();

}
